<template>
    <view class="container">
        <view class="content">
            <view class="list">
                <view class="item" @tap="tapitem(i)" :style="{marginTop:i.top?i.top:'1rpx'}" v-for="i in config" :key="i.key">
                    <view class="view">{{i.title}}</view>
                    <view>
                        <view class="text"
                              v-if="localData[i.key] !== null && localData[i.key] !== undefined"
                              :style="{ color: getStatusColor(i.key, localData[i.key]) }">
                            {{formatDataValue(i.key, localData[i.key])}}
                        </view>
                        <view class="text" v-else :style="{ color: '#07C160' }">空</view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>



<script>
    import request from "@/util/request";

    export default {
        name: "currentData",
        props: {
            config: {
                type: Array,
                default: () => [
                    { title: '设备识别码', key: 'equipmentId' },
                    { title: '数据发送时间', key: 'sendTime' },
                    { title: '通信状态', key: 'ctrlCommStatus' },
                    // 监控数据字段
                    { title: '漏电监测', key: 'leakageChannels' },
                    { title: '漏电通道使能', key: 'leakageLinkBit' },
                    { title: '漏电故障', key: 'leakageFaultBit' },
                    { title: '漏电报警', key: 'leakageAlarmBit' },
                    { title: '漏电值', key: 'leakageValue' },
                    { title: '温度监测', key: 'tempChannels' },
                    { title: '温度通道1使能', key: 'temp1LinkBit' },
                    { title: '温度通道1故障', key: 'temp1FaultBit' },
                    { title: '温度通道1报警', key: 'temp1AlarmBit' },
                    { title: '温度通道1', key: 'temp1' },
                    { title: '温度通道2使能', key: 'temp2LinkBit' },
                    { title: '温度通道2故障', key: 'temp2FaultBit' },
                    { title: '温度通道2报警', key: 'temp2AlarmBit' },
                    { title: '温度通道2', key: 'temp2' },
                    { title: '温度通道3使能', key: 'temp3LinkBit' },
                    { title: '温度通道3故障', key: 'temp3FaultBit' },
                    { title: '温度通道3报警', key: 'temp3AlarmBit' },
                    { title: '温度通道3', key: 'temp3' },
                    { title: '温度通道4使能', key: 'temp4LinkBit' },
                    { title: '温度通道4故障', key: 'temp4FaultBit' },
                    { title: '温度通道4报警', key: 'temp4AlarmBit' },
                    { title: '温度通道4', key: 'temp4' },
                    { title: 'DI1使能', key: 'di1LinkBit' },
                    { title: 'DI1联动报警', key: 'di1AlarmBit' },
                    { title: 'DI2使能', key: 'di2LinkBit' },
                    { title: 'DI2联动报警', key: 'di2AlarmBit' },
                    { title: 'DO1使能', key: 'do1LinkBit' },
                    { title: 'DO2使能', key: 'do2LinkBit' },
                    { title: 'A相电压', key: 'voltageA' },
                    { title: 'A相电流', key: 'currentA' },
                    { title: 'B相电压', key: 'voltageB' },
                    { title: 'B相电流', key: 'currentB' },
                    { title: 'C相电压', key: 'voltageC' },
                    { title: 'C相电流', key: 'currentC' },
                    { title: '有功功率', key: 'power' },
                    { title: '累计电能', key: 'energy' },
                    { title: '电压变比', key: 'ptRatio' },
                    { title: '电流变比', key: 'ctRatio' },
                    { title: '过压报警', key: 'overvoltage' },
                    { title: '欠压报警', key: 'undervoltage' },
                    { title: '缺相报警', key: 'phaseloss' },
                    { title: '过流报警', key: 'overcurrent' },
                    { title: '过载报警', key: 'overcapacity' },
                    { title: '数据域类型', key: 'ctrlDataDomain' },
                    { title: '应答标识', key: 'ctrlNeedAck' },
                    { title: '上报模式', key: 'ctrlReportMode' },
                    { title: '寻址模式', key: 'ctrlAddrMode' },
                ]
            },
            data: {
                type: Object,
                default: () => ({})
            }
        },
        data() {
            return {
                localData: {}
            };
        },
        onLoad(options) {
            console.log(options.equipmentId)
            this.equipmentInputStoreId = options.id;
            this.warnTime = options.warnTime;
            this.localData.equipmentId = options.equipmentId;
            this.fetchRealtimeData();
        },
        methods: {
            // 获取状态对应的颜色
            getStatusColor(key, value) {
                // 报警状态字段（值为1时报警）
                const alarmKeys = [
                    'leakageAlarmBit', 'temp1AlarmBit', 'temp2AlarmBit', 'temp3AlarmBit', 'temp4AlarmBit',
                    'di1AlarmBit', 'di2AlarmBit', 'overvoltage', 'undervoltage', 'phaseloss', 'overcurrent', 'overcapacity'
                ];

                // 故障状态字段（值为1时故障）
                const faultKeys = [
                    'leakageFaultBit', 'temp1FaultBit', 'temp2FaultBit', 'temp3FaultBit', 'temp4FaultBit',
                    'di1FaultBit', 'di2FaultBit'
                ];

                // 特殊状态字段
                const specialKeys = {
                    'ctrlCommStatus': value => value === 0 ? '#FF0000' : '#07C160' // 0=异常(红)，1=正常(绿)
                };

                // 检查特殊字段
                if (specialKeys[key]) {
                    return specialKeys[key](value);
                }

                // 报警字段处理
                if (alarmKeys.includes(key)) {
                    return value === 1 ? '#FF0000' : '#07C160';
                }

                // 故障字段处理
                if (faultKeys.includes(key)) {
                    return value === 1 ? '#999999' : '#07C160';
                }

                // 默认正常状态（绿色）
                return '#07C160';
            },
            // 格式化数据显示
            formatDataValue(key, value) {
                // 处理特殊字段的显示格式
                if (key === 'ctrlCommStatus') {
                    return value === 1 ? '正常' : '异常';
                }
                if (key === 'leakageLinkBit' || key === 'temp1LinkBit' || key === 'temp2LinkBit' || key === 'temp3LinkBit' || key === 'temp4LinkBit') {
                    return value === 1 ? '开启' : '关闭';
                }
                if (key === 'di1LinkBit' || key === 'di2LinkBit' || key === 'do1LinkBit' || key === 'do2LinkBit') {
                    return value === 1 ? '闭合' : '断开';
                }
                if (key === 'leakageAlarmBit' || key === 'temp1AlarmBit' || key === 'temp2AlarmBit' || key === 'temp3AlarmBit' || key === 'temp4AlarmBit' || key === 'di1AlarmBit' || key === 'di2AlarmBit' || key === 'overvoltage' || key === 'undervoltage' || key === 'phaseloss' || key === 'overcurrent' || key === 'overcapacity') {
                    return value === 1 ? '报警' : '正常';
                }
                if (key === 'leakageFaultBit' || key === 'temp1FaultBit' || key === 'temp2FaultBit' || key === 'temp3FaultBit' || key === 'temp4FaultBit' || key === 'di1FaultBit' || key === 'di2FaultBit') {
                    return value === 1 ? '故障' : '正常';
                }
                if (key === 'ctrlDataDomain') {
                    return value === 0 ? '数据域' : value === 1 ? '设置域' : '控制域';
                }
                if (key === 'ctrlNeedAck') {
                    return value === 1 ? '需应答' : '无需应答';
                }
                if (key === 'ctrlReportMode') {
                    return value === 0 ? '主机轮询' :
                        value === 1 ? '从机应答' :
                            value === 2 ? '定时上报' : '变位上报';
                }
                if (key === 'ctrlAddrMode') {
                    return value === 0 ? '四级地址' :
                        value === 1 ? '设备ID' :
                            value === 2 ? '逻辑地址' : '广播';
                }

                // 添加单位
                if (key === 'leakageChannels') {
                    return value + "通道";
                }

                if (key.includes('temp') || key === 'leakageValue') {
                    if (key === "tempChannels") {
                        return value + "通道";
                    } else {
                        return value + (key === 'leakageValue' ? ' mA' : '°C');
                    }
                }
                if (key.includes('voltage') || key.includes('current')) {
                    return value + (key.includes('voltage') ? ' V' : ' A');
                }
                if (key === 'power') return value + ' kW';
                if (key === 'energy') return value + ' kWh';
                if (key.includes('harmonics')) return value + '%';
                if (key === 'ptRatio' || key === 'ctRatio') return value + '倍';

                return value;
            },

            // 从后端接口获取实时数据
            // 修正后的代码
            async fetchRealtimeData() {
                try {
                    let response = await request.get(`/sdf300-current-data/${this.equipmentInputStoreId}`);
                    if (response.data) {
                        console.log('获取实时数据成功:', response.data);
                        this.parseRealtimeData(response.data);
                    }
                } catch (error) {
                    console.error('获取实时数据失败:', error);
                }
            },

            // 解析实时数据到当前组件
            parseRealtimeData(data) {
                // 同时更新到列表数据
                Object.keys(data).forEach(key => {
                    this.$set(this.localData, key, data[key]);
                });
            },

            getUrl(url){
                if(!url){
                    return null;
                }

                const urlResult = {type: "String", data: ""};
                if(url.includes(',')){
                    const urlList = url.split(',');
                    return {
                        type: "Array",
                        data: urlList
                    };
                }

                return {
                    type: "String",
                    data: url
                };
            },

            tapitem(info) {
                console.log('点击项:', info);
            }
        }
    }
</script>

<style lang="scss" scoped>
    @import url("@/common/globleCSS/photoPreview.css");
    .container {
        height: 100%;
        padding-bottom: constant(safe-area-inset-bottom);
        /* 适配iOS<11.2 */
        padding-bottom: env(safe-area-inset-bottom);
        /* 适配iOS>11.2 */
    }

    .content {
        height: 100%;
        /* 假设底部吸底栏高度为50px */
        overflow-y: auto;
        /* 开启滚动 */
    }

    .list {
        display: flex;
        flex-direction: column;
        background-color: #f2f2f2;
    }

    .item {
        display: flex;
        align-items: center;
        background-color: #fff;
        justify-content: space-between;
        flex-wrap: wrap;
        padding: 0 30rpx;

        &:active {
            background-color: #f2f2f2;
        }

        .view {
            padding: 30rpx 0;
            font-size: 14px;
            flex: 1;
            color: #333333;
        }

        .text {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 0;
            overflow: hidden;
            font-size: 14px;
            color: #999;
        }
    }
</style>
